# -*- coding: utf-8 -*-

import cgi
import sys, os
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import facebook
from facebook import FacebookError

FACEBOOK_API_KEY = 'a8dfbf5416044ed379eaf8a4bb424fdf'
FACEBOOK_SECRET_KEY = 'e950aa7805c18e5fa6223367810a5e3d'
_DEBUG = True

def intiFB(self):
    fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
    if fb.check_session(self.request) and fb.added:
        return fb
    else:
        url = fb.get_add_url()
        self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
        return False

class MainPage(webapp.RequestHandler):
    def get(self):
    #def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        
        self.response.out.write('WORK')
    #get friend list begin
        friend_ids = fb.friends.get()
        friend_ids.append(fb.uid)
        
        info = fb.users.getInfo(friend_ids, ['name', 'pic_square', 'uid'])
        template_values={}
        template_values={'info': info}
    #get friend list end
        
    #2009.1006 render name picture begin
        #values = {'request': self.request}
        #values.update(template_values)
        #self.response.out.write(template.render('friend.html', values))
    #2009.1006 render name picture end
        
    #2009.1006 do not render begin
        #for i in info:
        #    self.response.out.write('<img src='+i['pic_square']+' />'+i['name']+'<br />')
    #2009.1006 do not render end    

    #2009.1007 get users item begin
        #info = fb.users.getInfo([fb.uid], ['name','pic_square', 'birthday', 'affiliations', 'sex'])[0]

        #self.response.out.write('''<html xmlns="http://www.w3.org/1999/xhtml">
#<head>
#<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>''')
        
        #for attr in info:
        #     '%s: %s' % (attr, info[attr])

        #friends = fb.friends.get()
        #friends = fb.users.getInfo(friends, ['name', 'birthday', 'relationship_status'])

        #for friend in friends:
        #    if 'birthday' in friend:
        #        self.response.out.write( friend['name']+ u'生日是'+ friend['birthday']+ u'目前是'+ friend['relationship_status']+'<br />')
        #    else:
        #        self.response.out.write( friend['name']+ u'沒有生日目前是'+ friend['relationship_status']+'<br />')

        #arefriends = fb.friends.areFriends([friends[0]['uid']], [friends[1]['uid']])

        #photos = fb.photos.getAlbums(friends[1]['uid'])
        #print photos
        #self.response.out.write('</body></html>')
    #2009.1007 get users end
    
        
    #2009.1007 fbml begin
        #fb.users.setStatus('API hello',null.false,true)
        #self.response.out.write('work')
    #2009.1007 fbml end
        
        

class FBML(webapp.RequestHandler):
    def get(self):
        self.response.out.write('hello get<fb:name>')
 
    def post(self):
        self.response.out.write('hello post<fb:name uid="loggedinuser"/>')

        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        friend_ids = fb.friends.get()
        friend_ids.append(fb.uid)
        
        info = fb.users.getInfo(friend_ids, ['name', 'pic_square', 'uid'])
        template_values={}
        template_values={'info': info}
        
        for i in info:
            self.response.out.write('<br /><fb:profile-pic uid="')                                            
            self.response.out.write(i['uid'])
            self.response.out.write(' />')

            self.response.out.write('''<fb:name uid=%s                
            

            ''')
            
            #self.response.out.write('<br /><fb:name uid=%s>' % i['uid'])

class FBJS(webapp.RequestHandler):
    def get(self):
        pass
    def post(self):
        self.response.out.write(template.render('FBJS.html',0))
        
class Utility(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('Utility.js',0))

class FBjqRY(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('FBjqRY.min.js',0))

class msg(webapp.RequestHandler):
    def get(self):
        self.response.out.write('hahaha')
    def post(self):
        self.response.out.write(u'聽說 聽說很好看')

class publishArtcle(webapp.RequestHandler):
    def post(self):
        #self.response.out.write('hello post<fb:name uid="loggedinuser"/>')

        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        
        #title = render('news')
        try:
            if not fb.feed.publishActionOfUser(title='yes'):
                # Yet another way this can fail.
                raise FacebookError("Permission error")
            log.debug("Publish action of user for uid:%s" % facebook.uid)
        except FacebookError, e:
            # There's no need to tell the user.
            log.debug("Could not publish news item:%r" % e)
        self.response.out.write(u'聽說 聽說很好看')

class userProfile(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        
        #fb.profile.setFBML('<fb:wide>Woot!</fb:wide>', fb.uid)
        
        #beok = fb.users.setStatus('hellllllo',fb.uid,False,True)
        
        beok = fb.status.set('ok' )
        #beok = fb.feed.publishStoryToUser('work','gogo','http://www.qlkj.net.cn/ShowPic.ashx?CategoryID=1&ItemID=20928&Size=O&PicNO=1','http://www.qlkj.net.cn/ShowPic.ashx?CategoryID=1&ItemID=20928&Size=O&PicNO=1')
        #beok = fb.users.hasAppPermission('status_update',null)
        #_FbTemplateBundleId = 187480980249
        #pledge = Pledge()
        #pledge.authorfid = info['uid']
        #pledge.author = info['name']
        #pledge.content = userpledge 
        #beok = fb.feed.publishUserAction(_FbTemplateBundleId,'{"images":[{"src":"http://img5.imageshack.us/img5/7762/akomismoicon2.jpg","href":"http://apps.facebook.com/akomismo"},{"src":"http://img5.imageshack.us/img5/7762/akomismoicon2.jpg","href":"http://apps.facebook.com/akomismo"}],"pledge":"'+userpledge+'"}',[],1)
        #pledge.put()

        self.response.out.write(beok)
        self.response.out.write(u'聽說 聽說很好看<fb:name uid=%s />' % fb.uid)
        #self.response.out.write('<fb:prompt-permission perms="publish_stream" >Click</fb:prompt-permission>')

class keepShowMsg(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return

        

        word='''
        1
        3
        5
        '''
        
        content='''<script src="http://118.169.31.35/Utility.js"></script>
<script src="http://118.169.31.35/FBjqRY.min.js"></script>
<script language="javascript">
var g_timer=5;
setInterval(function()
{
	$('#timer').text(g_timer);
	g_timer=g_timer-1;
	if(g_timer==0)
	{
		$('#timer').text(1000);
		location.reload();
	}
},1000);

</script>
<div id="timer" > </div>


    `   <fb:name uid=%s /> send ok ,it would sent again 30mins later'''
        fb.status.set(word)
        self.response.out.write('ok')
        self.response.out.write(content % fb.uid)

class GetFriendList((webapp.RequestHandler):
    def post(self):
        #fb=intiFB(self)
        #fb.fql.query('SELECT ')
                    
        


def main():
    application = webapp.WSGIApplication([
        ('/',MainPage),
        #('/', FBML),
        ('/getparm',GetParm)
        ('/Utility.js', Utility),
        ('/FBjqRY.min.js', FBjqRY),
        ('/msg',msg)
        ],debug=_DEBUG)
    wsgiref.handlers.CGIHandler().run(application)
    
if __name__ == "__main__":
    main()

